class MyPromise {
  constructor(executor) {
    this.status = PENDING;
    this.value = undefined;
    this.reason = undefined;
    this.onFulfilledCallbacks = [];
    this.onRejectedCallbacks = [];

    const resolve = value => {
      if (this.status === PENDING) {
        this.status = FULFILLED;
        this.value = value;
        // 依次执行成功的回调函数
        this.onFulfilledCallbacks.forEach(callback => callback());
      }
    };

    const reject = reason => {
      if (this.status === PENDING) {
        this.status = REJECTED;
        this.reason = reason;
        // 依次执行失败的回调函数
        this.onRejectedCallbacks.forEach(callback => callback());
      }
    };

    try {
      // debugger;
      // 执行 executor 函数
      executor(resolve, reject);
    } catch (error) {
      // 如果 executor 函数抛出错误，调用 reject 方法
      reject(error);
    }
  }

  then(onFulfilled, onRejected) {
    // 处理 onFulfilled 不是函数的情况
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
    // 处理 onRejected 不是函数的情况
    onRejected =
      typeof onRejected === 'function'
        ? onRejected
        : reason => {
            throw reason;
          };

    const newPromise = new MyPromise((resolve, reject) => {
      const handleFulfilled = () => {
        try {
          const result = onFulfilled(this.value);
          // 处理 then 方法返回值
          resolvePromise(newPromise, result, resolve, reject);
        } catch (error) {
          reject(error);
        }
      };

      const handleRejected = () => {
        try {
          const result = onRejected(this.reason);
          // 处理 then 方法返回值
          resolvePromise(newPromise, result, resolve, reject);
        } catch (error) {
          reject(error);
        }
      };

      if (this.status === FULFILLED) {
        // 如果状态已经是 fulfilled，异步执行成功回调
        setTimeout(handleFulfilled, 0);
      } else if (this.status === REJECTED) {
        // 如果状态已经是 rejected，异步执行失败回调
        setTimeout(handleRejected, 0);
      } else {
        // 如果状态是 pending，将回调函数存储起来
        this.onFulfilledCallbacks.push(() => setTimeout(handleFulfilled, 0));
        this.onRejectedCallbacks.push(() => setTimeout(handleRejected, 0));
      }
    });

    return newPromise;
  }

  catch(onRejected) {
    // 调用 then 方法，只处理失败情况
    return this.then(null, onRejected);
  }

  finally(callback) {
    return this.then(
      value => {
        // 成功时先执行回调函数，再返回原 Promise 的值
        return MyPromise.resolve(callback()).then(() => value);
      },
      reason => {
        // 失败时先执行回调函数，再抛出原 Promise 的错误
        return MyPromise.resolve(callback()).then(() => {
          throw reason;
        });
      }
    );
  }

  static resolve(value) {
    if (value instanceof MyPromise) {
      // 如果传入的是 MyPromise 实例，直接返回
      return value;
    }
    // 否则返回一个已解决的 MyPromise 实例
    return new MyPromise(resolve => resolve(value));
  }

  static reject(reason) {
    // 返回一个已拒绝的 MyPromise 实例
    return new MyPromise((_, reject) => reject(reason));
  }

  static all(promises) {
    return new MyPromise((resolve, reject) => {
      const results = [];
      let completedCount = 0;

      if (promises.length === 0) {
        // 如果传入的数组为空，直接 resolve 空数组
        resolve(results);
        return;
      }

      promises.forEach((promise, index) => {
        // 将每个元素转换为 Promise 对象
        MyPromise.resolve(promise)
          .then(value => {
            results[index] = value;
            completedCount++;
            if (completedCount === promises.length) {
              // 所有 Promise 都成功完成，resolve 结果数组
              resolve(results);
            }
          })
          .catch(reason => {
            // 只要有一个 Promise 失败，就 reject
            reject(reason);
          });
      });
    });
  }

  static race(promises) {
    return new MyPromise((resolve, reject) => {
      promises.forEach(promise => {
        // 将每个元素转换为 Promise 对象
        MyPromise.resolve(promise)
          .then(value => {
            // 只要有一个 Promise 成功，就 resolve
            resolve(value);
          })
          .catch(reason => {
            // 只要有一个 Promise 失败，就 reject
            reject(reason);
          });
      });
    });
  }
}

function resolvePromise(newPromise, result, resolve, reject) {
  if (newPromise === result) {
    // 避免循环引用
    return reject(new TypeError('Chaining cycle detected for promise'));
  }

  if (result instanceof MyPromise) {
    // 如果 result 是 MyPromise 实例，等待其状态确定
    result.then(value => resolvePromise(newPromise, value, resolve, reject), reject);
  } else if (result !== null && (typeof result === 'object' || typeof result === 'function')) {
    try {
      const then = result.then;
      if (typeof then === 'function') {
        // 如果 result 有 then 方法，将其视为 thenable 对象
        let called = false;
        then.call(
          result,
          value => {
            if (called) return;
            called = true;
            resolvePromise(newPromise, value, resolve, reject);
          },
          reason => {
            if (called) return;
            called = true;
            reject(reason);
          }
        );
      } else {
        // 如果 result 没有 then 方法，直接 resolve
        resolve(result);
      }
    } catch (error) {
      if (called) return;
      called = true;
      reject(error);
    }
  } else {
    // 如果 result 是普通值，直接 resolve
    resolve(result);
  }
}

// 以下是使用示例
const promise1 = new MyPromise(resolve => setTimeout(() => resolve(1), 1000));
const promise2 = new MyPromise(resolve => setTimeout(() => resolve(2), 2000));
// 测试 Promise.all
MyPromise.all([promise1, promise2])
  .then(values => {
    console.log('Promise.all result:', values);
  })
  .catch(error => {
    console.error('Promise.all error:', error);
  });

// 测试 Promise.race
MyPromise.race([promise1, promise2])
  .then(value => {
    console.log('Promise.race result:', value);
  })
  .catch(error => {
    console.error('Promise.race error:', error);
  });

// 测试 Promise.prototype.finally
promise1
  .finally(() => {
    console.log('Promise finally executed');
  })
  .then(value => {
    console.log('Promise finally then value:', value);
  })
  .catch(error => {
    console.error('Promise finally catch error:', error);
  });

// const op = new Promise((resolve, reject) => {
//   // setTimeout(() => {
//   resolve(1);
//   // reject(2);
//   // }, 1000);
// });
// setTimeout(() => {
//   op.then(
//     value => {
//       // console.log('原生-成功回调1', value);
//       return new Promise((resolve, reject) => {
//         resolve(222222222);
//       });
//     },
//     error => {
//       // console.log('原生-失败回调1', error);
//     }
//   ).then(
//     value => {
//       // console.log('原生-成功回调1完成后', value);
//     },
//     error => {
//       // console.log('原生-失败回调2', error);
//     }
//   );

//   const op2 = op.then(res => {
//     return p2;
//   });
//   op.then(
//     value => {
//       // console.log('原生-成功回调1完成后', value);
//     }
//     // error => {
//     //   console.log('原生-error', error);
//     // }
//   );
// }, 1000)
